#!/usr/bin/env python
# coding=utf-8
# author:wade
# contact: 317909531@qq.com
# datetime:2021/1/2 21:41

"""
文件说明：基础类，生成模板使用
"""
import copy
import random
import re
import logging
import requests
import json


# 构造文章的基础,输入基本信息，构造出评论列表和图片列表
class Tools_Template(object):
    def __init__(self, title, commentList, imgList, itemURL, shopUrl, **kwargs):

        """
        本函数需要有40条评论和10个图片才能运行，在调用前需要做好判断

        :param title: 生成文案的标题
        :param commentList: 生成文案的评论列表
        :param imgList: 生成文案的图片列表
        :param itemURL: 自己的商品推广链接
        :param shopUrl: 自己的店铺推广链接
        :return 产出文章
        :templateFactory_forDiscuz Return:主句字符串和评论列表
        """
        random.shuffle(commentList)
        random.shuffle(imgList)
        self.title = title
        self.commentList = commentList
        self.imgList = imgList
        self.itemURL = itemURL
        self.shopUrl = shopUrl
        self.kwargs = kwargs
        self.ifRun = True
        self.pinglunList = []  # 论坛跟帖专用
        self.content = ''  # 论坛跟帖专用

    def wordJoin_imgJoin(self):
        # 这个函数是处理的核心，输出的内容是一段一段的，[一组话，加上几张配图],后边只需要判断非空就行了
        words = []
        imgs = []
        countWORD = 0

        P = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]  # 文章段落排版，如果没有图片了，就不再进行编入
        I = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
        # 第一次循环检查需求条数是否超出评论总量，如果不超出，就生成
        # 第二次循环检查需求条数是否超出评论剩余，如果不超出，就生成
        for runTime, num in enumerate(P):
            if P[runTime] <= len(self.commentList) - countWORD:  # 检查组合后剩余条数
                # 根据要求进行循环
                # print('开始使用', (countWORD, countWORD + P[runTime]))
                words.append(''.join(self.commentList[countWORD:countWORD + P[runTime]]))  # 第0段
                # 统计已经用掉多少条
                countWORD = countWORD + num
                # print('剩余条数', len(self.commentList) - countWORD)


        # 验证生产环境
        articleList = []
        imgLists = []
        imgLists = self.imgList[2:].copy()
        """
            0 one
            1 two
            2 three
        """
        for cout, i in enumerate(words,start=0):
            imgss = []
            if len(I) > cout:
                # print(len(I),cout)

                for item in range(I[cout]):
                    if imgLists != []:
                        imgss.append(imgLists.pop(0))
                    else:
                        imgss = []
            else:
                mgss = []
            articleList.append([i, imgss])
        return articleList

    def templateFactory_forDiscuz(self,longUrl):
        self.words = self.wordJoin_imgJoin()

        # 主要内容：1段话，2张图片
        # 如果只有一句话，没有图： 如果只有一句话 一张图：如果只有一句话2张图，如果只有1句话 3张图，如果只有2句话

        if len(self.words) > 2 and len(self.imgList) >= 2:
            self.content = f'''[font=&quot;]{self.words[0][0]}[/font]
        [font=&quot;][b][size=4]关于产品质量怎么样，以下供参考：[/size][/b]
        [/font][b][size=4][color=#ff0000]【千万不要被骗了】查看官网最新报价[/color][/size][/b][font=&quot;][color=#ff0000][size=4][b]：[/b][/size][/color][/font][font=arial, Tahoma, Verdana, STHeiTi, simsun, sans-serif, 宋体][size=5][color=#00bfff][b][url={longUrl}]点击查看[/url][/b][/color][/size][/font]
        [font=&quot;][color=#ff0000][/color][/font][font=&quot;][color=#ff0000][size=4][b]产品性能，使用感受综合评测：[/b][/size][/color][/font][font=arial, Tahoma, Verdana, STHeiTi, simsun, sans-serif, 宋体][size=5][color=#00bfff][b][url={longUrl}]点击查看[/url][/b][/color][/size][/font]
        [img=400,400]http://{self.imgList[0]}[/img]
        [img=400,400]http://{self.imgList[1]}[/img]'''

            for index, item in enumerate(self.words, start=1):
                pinglunWord = f'''[font=&quot]{item[0]}[/font]
                '''
                for imgRealLink in item[1]:
                    pinglunWord = pinglunWord+f'''[img]http://{imgRealLink}[/img]
                    '''
                self.pinglunList.append(pinglunWord)
                del pinglunWord

            return self.content, self.pinglunList
        else:
            return [], []

    def templateFactory_forQb(self,jdid,shopid,shopname,skuName,item_MainImg,item_price,shotUrl, longUrl):
        self.words = self.wordJoin_imgJoin()
        # 京东id/店铺id/店铺名称/产品名称/产品主图/产品价格/////
        """返回self.content 字符串"""
        if self.words != []:
            self.content = f'''{self.words[0][0]}
                        <p><strong><span style="font-size: big;color: black;">【千万不要被骗了】点击下方链接查看官网最新报价</span></strong></p>
        <div>
        <a style="background-color: #f6f6f6;
          display: block;
          border-radius: 8px;
          box-shadow:0px 0px 10px 5px #aaa;
          overflow: hidden;
          color: inherit;
          margin: 1em auto;
          max-width: 100%;
          min-height: 88px;
          position: relative;
          text-decoration: none;
          width: 390px;
          z-index: 0;"
           href="{longUrl}">
            <div style="-webkit-box-align: stretch;
                -ms-flex-align: stretch;
                align-items: stretch;
                position: relative;
                display: -webkit-box;
                display: -ms-flexbox;
                display: flex;
                overflow: hidden;
                max-width: 400px;
                min-height: 88px;">
                <div style="-webkit-box-sizing: border-box;
                      box-sizing: border-box;
                      width: 100%;
                      padding: 14px;
                      z-index: 2;
                      -webkit-box-align: stretch;
                      -ms-flex-align: stretch;
                      align-items: stretch;
                      position: relative;
                      display: -webkit-box;
                      display: -ms-flexbox;
                      display: flex;">
                    <div style="flex-shrink: 0;
                            overflow: hidden;
                            position: relative;
                            border-radius: 6px;
                            height: 100px;
                            width: 100px;">
                        <img style="height: 100%;
                                  width: 100%;" src="{item_MainImg}"
                             alt="">
                    </div>
                    <div style="
                            display: -webkit-box;
                            display: -ms-flexbox;
                            display: flex;
                            -webkit-box-orient: vertical;
                            -webkit-box-direction: normal;
                            -ms-flex-direction: column;
                            flex-direction: column;
                            -webkit-box-flex: 1;
                            -ms-flex-positive: 1;
                            flex-grow: 1;
                            margin-left: 12px;
                            overflow: hidden;">
                        <div style="display: flex;-webkit-box-align: center;
                                  -ms-flex-align: center;
                                  align-items: center;
                                  -webkit-box-pack: justify;
                                  -ms-flex-pack: justify;
                                  justify-content: space-between;">
                            <div style="color: #121212;
                                        font-size: 16px;
                                        line-height: 20px;
                                        max-height: 40px;
                                        font-weight: 600;
                                        font-synthesis: style;
                                        display: -webkit-box;
                                        text-overflow: ellipsis;
                                        overflow: hidden;
                                        -webkit-line-clamp: 2;
                                        -webkit-box-orient: vertical;">{skuName}
                            </div>
                        </div>
                        <div style="color: #646464;
                              font-size: 12px;
                              line-height: 17px;
                              margin-top: 5px;
                              font-weight: 600;
                              font-synthesis: style;"> 京 东
                        </div>
                        <div style="display: -webkit-box;
                              display: -ms-flexbox;
                              display: flex;
                              -webkit-box-align: end;
                              -ms-flex-align: end;
                              align-items: flex-end;
                              margin-top: auto;">
                            <div style="margin-right: auto;display: block;">
                                <div class="MCNLinkCard-price" style="-webkit-box-align: center;
                              -ms-flex-align: center;
                              align-items: center;
                              color: #ff7955;
                              display: -webkit-box;
                              display: -ms-flexbox;
                              display: flex;
                              font-size: 16px;
                              font-weight: 500;
                              line-height: 18px;
                              margin-right: auto;">
                                    <span>¥ {item_price}</span></div>
                            </div>
                            <div style="display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -ms-flex-negative: 0;
            flex-shrink: 0;
            -webkit-box-pack: center;
            -ms-flex-pack: center;
            justify-content: center;
            -ms-flex-item-align: start;
            align-self: flex-start;
            -webkit-box-align: center;
            -ms-flex-align: center;
            align-items: center;
            color: #ff7955;
            font-size: 13px;
            height: 17px;
            line-height: 17px;
            font-weight: 600;
            font-synthesis: style;" role="button">去购买
                                <span style="display: inline-flex; align-items: center;">&#8203;</span></div>
                        </div>
                    </div>
                </div>
            </div>
        </a>
    </div>
'''
            for index, item in enumerate(self.words, start=1):
                for imgRealLink in item[1]:
                    self.content = self.content + f'''<img style="height: 100%;
                                  width: 100%;" src="http://{imgRealLink}" alt="" />'''
                self.content = self.content + f'''<p>{item[0]}</p>'''

        return self.content

    def templateFactory_forWeb(self,jdid,shopid,shopname,skuName,item_MainImg,item_price,shotUrl, longUrl):
        self.words = self.wordJoin_imgJoin()
        # 京东id/店铺id/店铺名称/产品名称/产品主图/产品价格/////
        """返回self.content 字符串"""
        if self.words != []:
            self.content = f'''{self.words[0][0]}
                        <p><strong><span style="font-size: big;color: black;">【千万不要被骗了】点击下方链接查看官网最新报价</span></strong></p>
        <div>
        <a style="background-color: #f6f6f6;
          display: block;
          border-radius: 8px;
          box-shadow:0px 0px 10px 5px #aaa;
          overflow: hidden;
          color: inherit;
          margin: 1em auto;
          max-width: 100%;
          min-height: 88px;
          position: relative;
          text-decoration: none;
          width: 390px;
          z-index: 0;"
           href="{longUrl}">
            <div style="-webkit-box-align: stretch;
                -ms-flex-align: stretch;
                align-items: stretch;
                position: relative;
                display: -webkit-box;
                display: -ms-flexbox;
                display: flex;
                overflow: hidden;
                max-width: 400px;
                min-height: 88px;">
                <div style="-webkit-box-sizing: border-box;
                      box-sizing: border-box;
                      width: 100%;
                      padding: 14px;
                      z-index: 2;
                      -webkit-box-align: stretch;
                      -ms-flex-align: stretch;
                      align-items: stretch;
                      position: relative;
                      display: -webkit-box;
                      display: -ms-flexbox;
                      display: flex;">
                    <div style="flex-shrink: 0;
                            overflow: hidden;
                            position: relative;
                            border-radius: 6px;
                            height: 100px;
                            width: 100px;">
                        <img style="height: 100%;
                                  width: 100%;" src="{item_MainImg}"
                             alt="">
                    </div>
                    <div style="
                            display: -webkit-box;
                            display: -ms-flexbox;
                            display: flex;
                            -webkit-box-orient: vertical;
                            -webkit-box-direction: normal;
                            -ms-flex-direction: column;
                            flex-direction: column;
                            -webkit-box-flex: 1;
                            -ms-flex-positive: 1;
                            flex-grow: 1;
                            margin-left: 12px;
                            overflow: hidden;">
                        <div style="display: flex;-webkit-box-align: center;
                                  -ms-flex-align: center;
                                  align-items: center;
                                  -webkit-box-pack: justify;
                                  -ms-flex-pack: justify;
                                  justify-content: space-between;">
                            <div style="color: #121212;
                                        font-size: 16px;
                                        line-height: 20px;
                                        max-height: 40px;
                                        font-weight: 600;
                                        font-synthesis: style;
                                        display: -webkit-box;
                                        text-overflow: ellipsis;
                                        overflow: hidden;
                                        -webkit-line-clamp: 2;
                                        -webkit-box-orient: vertical;">{skuName}
                            </div>
                        </div>
                        <div style="color: #646464;
                              font-size: 12px;
                              line-height: 17px;
                              margin-top: 5px;
                              font-weight: 600;
                              font-synthesis: style;"> 京 东
                        </div>
                        <div style="display: -webkit-box;
                              display: -ms-flexbox;
                              display: flex;
                              -webkit-box-align: end;
                              -ms-flex-align: end;
                              align-items: flex-end;
                              margin-top: auto;">
                            <div style="margin-right: auto;display: block;">
                                <div class="MCNLinkCard-price" style="-webkit-box-align: center;
                              -ms-flex-align: center;
                              align-items: center;
                              color: #ff7955;
                              display: -webkit-box;
                              display: -ms-flexbox;
                              display: flex;
                              font-size: 16px;
                              font-weight: 500;
                              line-height: 18px;
                              margin-right: auto;">
                                    <span>¥ {item_price}</span></div>
                            </div>
                            <div style="display: -webkit-box;
            display: -ms-flexbox;
            display: flex;
            -ms-flex-negative: 0;
            flex-shrink: 0;
            -webkit-box-pack: center;
            -ms-flex-pack: center;
            justify-content: center;
            -ms-flex-item-align: start;
            align-self: flex-start;
            -webkit-box-align: center;
            -ms-flex-align: center;
            align-items: center;
            color: #ff7955;
            font-size: 13px;
            height: 17px;
            line-height: 17px;
            font-weight: 600;
            font-synthesis: style;" role="button">去购买
                                <span style="display: inline-flex; align-items: center;">&#8203;</span></div>
                        </div>
                    </div>
                </div>
            </div>
        </a>
    </div>
'''
            for index, item in enumerate(self.words, start=1):
                for imgRealLink in item[1]:
                    self.content = self.content + f'''<img style="height: 100%;
                                  width: 100%;" src="http://{imgRealLink}" alt="" />'''
                self.content = self.content + f'''<p>{item[0]}</p>'''

        return self.content








# if __name__ == '__main__':
# #     # HTML,PingLUN = wade.templateFactory_forDiscuz()
#     jdid = 100008829953
# #     pages = 3  # 到淘宝爬取评论
#
#
#
#
# #
# #
# #     # 调用企业博客发帖模块函数块需要的内容----START
# #     bokeeconfig =ContentConfig()
# #     bokeeconfig.title = '【图文体验】峰米Smart评价怎么样？？觉得峰米投影仪好不好123'
# #     bokeeconfig.content = wade.templateFactory_forQb()
# #     bokeeconfig.columnName = '值得买'  # 分类名字1
# #     bokeeconfig.addType = '值得买'  # 分类2
# #     bokeeconfig.tags = ''  # 标签
# #     bokeeconfig.brief = ''  # 内容摘要
# #     bokeePOST(bokeeconfig)
# #     print(bokeeconfig.__dict__)
# #     # 调用企业博客发帖模块函数块需要的内容----END
#
#
#
# HEADERS = [
#     'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.75 Safari/537.36',
#     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
#     'Mozilla/5.0 (Windows;U;WindowsNT6.1;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50',
#     'Mozilla/5.0 (Macintosh;IntelMacOSX10.6;rv:2.0.1)Gecko/20100101Firefox/4.0.1',
#     'Mozilla/5.0 (Windows NT6.1;rv:2.0.1)Gecko/20100101Firefox/4.0.1',
#     'Mozilla/5.0 (Macintosh;IntelMacOSX10_7_0)AppleWebKit/535.11(KHTML,likeGecko)Chrome/17.0.963.56Safari/535.11',
#     'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36',
#     'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
#     'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:41.0) Gecko/20100101 Firefox/41.0',
#     'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko',
#     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
#     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.18362',
#     'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36',
#     'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0',
#     'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4098.3 Safari/537.36',
#     'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
#     'Mozilla/5.0 (Macintosh;U;IntelMacOSX10_6_8;en-us)AppleWebKit/534.50(KHTML,likeGecko)Version/5.1Safari/534.50',
#     'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586',
#     'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27',
#     'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.27 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/601.1.27',
#     'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36',
#     'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:70.0) Gecko/20100101 Firefox/70.0',
#     'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36',
# ]
#
#
# headers = {
#     'Accept': '*/*',
#     'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
#     'User-Agent': random.choice(HEADERS),
#     'Connection': 'keep-alive',
#     'Host': 'club.jd.com',
# }
# url= 'https://club.jd.com/productpage/p-100004079683-s-3-t-5-p-0.html?callback=fetchJSON_comment98vv37'
# html = requests.get(url=url, headers=headers)
# # print(html.text)
# content = html.text.split('({"')  # 收到的str内容进行清洗处理，变成可用的json
# print(content)
# flag_two = content[1].split('}]}')  # 收到的str内容进行清洗处理，变成可用的json
# print(flag_two)
# json_flag = json.loads(f'''{{"{flag_two[0]}}}]}}''', strict=False)  # 收到的str内容进行清洗处理，变成可用的json，处理好了
# print('jdmain运行成功（京东爬虫主程序）')
# print(json_flag)
#
#
